package com.xjscrm.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.TreeMap;


public class ApiSignUtil {
	private static Logger logger =  LoggerFactory.getLogger(ApiSignUtil.class);

	public static String getSign(TreeMap<String, Object> treeMap, String key) {
		if (treeMap==null) {
			return "";
		}
		String ascStr = toAscString(treeMap) + String.format("key=%s", key );
		logger.info("sign param:{}",ascStr);
		return DigestUtils.md5DigestAsHex(ascStr.getBytes());
	}
	private static String toAscString(TreeMap<String, Object> treeMap) {
		StringBuilder buf = new StringBuilder();
		try {
			Iterator<Entry<String, Object>> it = treeMap.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, Object> entry = it.next();
				//对一些特殊符号先进行转换成URL编码
				String value = entry.getValue().toString();
				value = value.replace("%","%25");
				value = value.replace("+","%2b");
				buf.append(String.format("%s=%s", entry.getKey(), URLDecoder.decode(value, "UTF-8")));
			}
		} catch (Exception e) {
			logger.error("getAscString.Exception:", e);
		}
		return buf.toString();
	}
}
